package com.baohulu.baohulu.activity.account;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.baohulu.baohulu.R;
import com.baohulu.baohulu.activity.TimerActivity;
import com.baohulu.baohulu.base.BaseResponseCallback;
import com.baohulu.baohulu.common.Const;
import com.baohulu.baohulu.utils.HttpUtil;
import com.baohulu.baohulu.utils.JsonUtil;
import com.baohulu.baohulu.utils.SharedPrefUtil;
import com.baohulu.baohulu.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginState extends AccountState {
    private static final String TAG = "LoginState";

    LoginState(AccountActivity activity) {
        super(activity);
    }


    @Override
    public void init() {
        mActivity.tvForgetPassword.setVisibility(View.VISIBLE);
        mActivity.tvConfirmPassword.setVisibility(View.GONE);
        mActivity.etConfirmPassword.setVisibility(View.GONE);
        mActivity.tvHintText.setText(R.string.user_login);
        mActivity.btnLogin.setText(R.string.login);
        mActivity.tvRegisterAcc.setText(R.string.register_account);
    }

    @Override
    public boolean isInputLegal() {
        phoneNumber = mActivity.etPhoneNumber.getText().toString();
        password = mActivity.etPassword.getText().toString();
        if (TextUtils.isEmpty(phoneNumber) || TextUtils.isEmpty(password)) {
            ToastUtil.showToast("用户名/密码不能为空");
        } else if (password.length() < 6) {
            ToastUtil.showToast("密码不能小于6位");
        } else if (isPhoneNumberInvalid(phoneNumber)) {
            ToastUtil.showToast("手机号码不合法");
        } else {
            return true;
        }
        return false;
    }

    @Override
    public void submitData() {
        String loginUrl = mActivity.getString(R.string.url_base) + mActivity.getString(R.string.url_user_login);
        JSONObject data = new JsonUtil.JsonBuilder()
                .put("account", phoneNumber)
                .put("password", password)
                .build();
        HttpUtil.post(mActivity, loginUrl, data, new BaseResponseCallback() {
            @Override
            public void onStart() {
                mActivity.showProgressDialog();
            }

            @Override
            public void onJsonObjectResponse(JSONObject jsonObject) {
                super.onJsonObjectResponse(jsonObject);
                try {
                    int state = jsonObject.getInt("state");
                    String account = "";
                    String nickname = "";
                    if (state == 1) {
                        account = jsonObject.getString("account");
                        nickname = jsonObject.getString("nickname");
                    }
                    resolveLoginResult(state, account, nickname);
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    mActivity.hideProgressDialog();
                }
            }

            @Override
            public void onFailure(String msg) {
                mActivity.hideProgressDialog();
                ToastUtil.showToast(msg);
            }
        });

    }

    /**
     * 处理登录结果
     *
     * @param state 0：帐户不存在；1：登录成功；2：密码错误
     */
    private void resolveLoginResult(int state, String account, String nickname) {
        switch (state) {
            case 0://帐户不存在
                ToastUtil.showToast(R.string.account_not_exist);
                break;
            case Const.ResponseState.SUCCESS://登录成功
                saveLoginState(account, nickname);
                checkUserRentState();
                break;
            case 2://密码错误
                ToastUtil.showToast(R.string.wrong_password);
                break;
        }
    }

    /**
     * 检查用户租借状态，如果用户处在租借状态，跳转到计时页面
     */
    private void checkUserRentState() {
        String url = mActivity.getString(R.string.url_base) + mActivity.getString(R.string.url_check_user_rent_state);
        HttpUtil.post(mActivity, url, new JSONObject(), new BaseResponseCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onJsonObjectResponse(JSONObject jsonObject) {
                super.onJsonObjectResponse(jsonObject);
                try {
                    int state = jsonObject.getInt("state");
                    if (state == 1) {//用户正在租借
                        long startTime = jsonObject.getLong("start_time");
                        String ballKey = jsonObject.getString("ball_key");
                        String eqKey = jsonObject.getString("eq_key");
                        int doorId = jsonObject.getInt("door_id");
                        double ballPrice = jsonObject.getDouble("ball_price");
                        //跳转到计时页面
                        jumpToTimerActivity(startTime, ballKey, eqKey, ballPrice, doorId);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    mActivity.finish();
                }
            }

            @Override
            public void onFailure(String msg) {
                Log.e(TAG, "检查用户租借状态失败: " + msg);
                mActivity.finish();
            }
        });
    }

    /**
     * 跳转到计时页面
     */
    private void jumpToTimerActivity(long startTime, String ballKey, String eqKey, double ballPrice, int doorId) {
        Intent intent = new Intent(mActivity, TimerActivity.class);
        intent.putExtra(Const.Extra.START_TIME, startTime)
                .putExtra(Const.Extra.BALL_PRICE, ballPrice)
                .putExtra(Const.Extra.EQ_KEY, eqKey)
                .putExtra(Const.Extra.BALL_KEY, ballKey)
                .putExtra(Const.Extra.DOOR_INDEX, doorId);
        mActivity.startActivity(intent);
    }

    private void saveLoginState(String account, String nickname) {
        SharedPrefUtil.putString(Const.SpKey.LOGIN_USER_ACCOUNT, account);
        SharedPrefUtil.putBoolean(Const.SpKey.IS_LOGIN, true);
        //如果昵称为空，则将帐号作为昵称
        SharedPrefUtil.putString(Const.SpKey.LOGIN_USER_NICKNAME, TextUtils.isEmpty(nickname) ? account : nickname);
        ToastUtil.showToast(R.string.login_success);
    }


    @Override
    public void forgetPassword() {
        //处理忘记密码逻辑
        ToastUtil.showToast("忘记密码！");
    }
}
